package com.example.administrator.im.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.im.MyApplication;
import com.example.administrator.im.R;
import com.example.administrator.im.config.ImageConfig;
import com.example.administrator.im.db.FriendDBHelper;
import com.example.administrator.im.db.UserDBHelper;
import com.example.administrator.im.utils.DownloadImageUtils;
import com.example.administrator.im.utils.EMUtils;
import com.example.administrator.im.data.IMData;
import com.example.administrator.im.ui.activity.ChatRoomActivity;
import com.example.administrator.im.ui.activity.HomeActivity;
import com.example.administrator.im.ui.fragment.IMFragment;
import com.example.administrator.im.utils.FileUtils;
import com.example.administrator.im.utils.HttpUtils;
import com.example.administrator.im.view.IM_Item;
import com.hyphenate.chat.EMMessage;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * create:2018/9/16 22:32
 * author: 姚鸿杰
 **/
public class IMItemAdapter extends RecyclerView.Adapter<IMItemAdapter.Holder> {

    private final String TAG = "IMItemAdapter";

    private Context mContext;
    private List<IMData> mList;

    //类型 头部或者正常布局
    private final static int TYPE_HEADER = 0;
    private final static int TYPE_BODY = 1;

    //头部布局 目前只能添加一个
    private View mHeaderView;

    //添加头部布局
    public void addHeaderView(View header) {
        mHeaderView = header;

        //默认添加头第0位置
        notifyItemInserted(0);
        notifyItemRangeChanged(1, getItemCount());
    }


    //初始化
    public IMItemAdapter(Context mContext, List<IMData> mList) {
        this.mContext = mContext;
        if (mList == null) {
            this.mList = new ArrayList<>();
        } else {
            this.mList = mList;
        }
    }

    public void addItem(List<IMData> mList) {
        this.mList = mList;
        notifyDataSetChanged();
    }

    /**
     * 更新会话类表
     *
     * @param conversation 会话
     */
    public void updateData(IMFragment.UpdateConversations conversation) {

        String username = conversation.getMsg().getUserName();    //获取发送者账号
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).getMsg().getUserName().equals(username)) {   //如果该会话对象存在
                mList.remove(i);
                break;
            }
        }
        //将会话添加到头部
        mList.add(0, new IMData(conversation.getMsg(), conversation.isAcked()));
        //更新会话
        notifyDataSetChanged();
    }

    /**
     * 标记为已读
     */
    public void setIsAcked(String username) {

        if (mList != null && mList.size() > 0) {
            for (int i = 0; i < mList.size(); i++) {
                if (username.equals(mList.get(i).getMsg().getUserName())) {
                    mList.get(i).setAcked(true);
                    notifyDataSetChanged();
                }
            }
        }

    }

    /**
     * 获取接收消息时的时间
     *
     * @param currentTime 获取是的秒数
     * @return 返回格式为小时：分钟
     */
    private String getTimeShort(long currentTime) {
        SimpleDateFormat formatterMsg = new SimpleDateFormat("dd:HH:mm");
        SimpleDateFormat formatterNow = new SimpleDateFormat("dd");

        Date dateMsg = new Date(currentTime);
        Date dateNow = new Date(System.currentTimeMillis());
        String date_msg = formatterMsg.format(dateMsg);
        String date_now = formatterNow.format(dateNow);

        String[] datesMsg = date_msg.split(":");
        if (date_now.equals(datesMsg[0])) {
            return datesMsg[1] + ":" + datesMsg[2];
        } else {
            if (Integer.valueOf(datesMsg[0]) + 1 == Integer.valueOf(date_now)) {
                return "昨天";
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd");
        Date date = new Date(currentTime);
        return sdf.format(date);
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {

        //如果类型为TYPE_HEADER并且头部布局不为空则加载头部布局
        if (viewType == TYPE_HEADER && mHeaderView != null) {
            return new Holder(mHeaderView);
        }

        //否则正常加载
        View v = LayoutInflater.from(mContext).inflate(R.layout.im_item, viewGroup, false);
        return new Holder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {

        //如果有头部布局并且position为0则直接返回不进行操作
        if (getItemViewType(position) == TYPE_HEADER) {
            return;
        }

        //如果有头部布局存在，他会占据0位置，所以position必须减1
        if (mHeaderView != null) {
            position--;
        }

        final IMData data = mList.get(position);
        EMMessage msg = data.getMsg();

        String img_path = "";
        String nickname = "";
        String direct = "";
        String username = "";

        if (msg.direct() == EMMessage.Direct.SEND) {   //表示发送方
            FriendDBHelper friend = LitePal.where("username = ?", msg.getTo()).findFirst(FriendDBHelper.class);
            //获取接收方的头像地址
            if (friend != null) {
                username = friend.getUsername();
                img_path = friend.getImg_path();
                nickname = TextUtils.isEmpty(friend.getRemarks()) ?
                        friend.getNickname() : friend.getRemarks();
            }
        } else {
            FriendDBHelper friend = LitePal.where("username = ?", msg.getUserName()).findFirst(FriendDBHelper.class);
            if (friend != null) {
                username = friend.getUsername();
                nickname = TextUtils.isEmpty(friend.getRemarks()) ?
                        friend.getNickname() : friend.getRemarks();
                direct = nickname + "：";
            }
            img_path = msg.getStringAttribute("imgUrl", "");
        }

        int what = msg.getIntAttribute("type", -1);
        String content = what == EMUtils.IMAGE ? "[图片]" : EMUtils.getContent(msg);   //获取内容
        String time = getTimeShort(msg.getMsgTime());   //获取消息时间
        String account = msg.getUserName(); //通话对象

        //加载头像
        String url = HttpUtils.PORT + img_path;
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.login_logo)
                .error(R.mipmap.login_logo)
                .override(ImageConfig.getItemSmall(), ImageConfig.getItemSmall());

        Glide.with(mContext).load(url).apply(options).into(holder.img_icon);


        holder.tv_title.setText(nickname);
        holder.read_msg.setVisibility(mList.get(position).isAcked() ? View.GONE : View.VISIBLE);
        holder.btn_read.setVisibility(mList.get(position).isAcked() ? View.GONE : View.VISIBLE);

        holder.tv_content.setText(content);
        holder.tv_time.setText(time);

        holder.rl.setOnClickListener(new ItemClick(account, nickname));
        holder.btn_topping.setOnClickListener(new ItemClick(position + 1));
        holder.btn_read.setOnClickListener(new ItemClick(position + 1, account));
        holder.btn_delete.setOnClickListener(new ItemClick(position + 1, account));
    }


    @Override
    public int getItemCount() {
        return mHeaderView == null ? mList.size() : mList.size() + 1;
    }

    /**
     * @param position 第几个位置
     * @return 返回该位置的布局类型
     */
    @Override
    public int getItemViewType(int position) {

        if (mHeaderView == null)    //如果头布局不存在则返回TYPE_BODY类型
            return TYPE_BODY;
        if (position == 0) {    //如果存在并且位置为0 则返回头部TYPE_HEADER类型
            return TYPE_HEADER;
        }
        return TYPE_BODY;   //否则直接返回TYPE_BODY
    }


    class ItemClick implements View.OnClickListener {
        private int position;
        private String username;
        private String nickname;

        ItemClick(int position) {
            this.position = position;
        }

        ItemClick(String username, String nickname) {
            this.username = username;
            this.nickname = nickname;
        }


        ItemClick(int position, String username) {
            this.position = position;
            this.username = username;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.msg:
                    if (IM_Item.isIs_open()) {
                        IM_Item.getIm_item().closeMenu();
                        return;
                    }
                    Intent intent = new Intent(mContext, ChatRoomActivity.class);
                    intent.putExtra("username", username);
                    intent.putExtra("nickname", nickname);
                    mContext.startActivity(intent);
                    break;
                case R.id.topping:
                    Toast.makeText(mContext, "置顶" + position, Toast.LENGTH_SHORT).show();
                    break;
                case R.id.read:
                    setIsAcked(position, username);
                    break;
                case R.id.delete:
                    IM_Item.getIm_item().closeMenu();
                    EMUtils.removeConversation(username, false);
                    remove(position);
                    return;
            }
            IM_Item.getIm_item().closeMenu();
        }
    }

    //标记为已读
    private void setIsAcked(int position, String username) {
        mList.get(position - 1).setAcked(true);
        EMUtils.setMsgAcked(username);
        notifyItemChanged(position);
        EventBus.getDefault().post(new HomeActivity.UpdateIsAckedCount());
    }

    //移除一条会话
    private void remove(int position) {
        if (mList != null) {
            mList.remove(position - 1);
            notifyItemRemoved(position);
            if (position != mList.size()) {
                notifyItemRangeChanged(position, mList.size() - position);
            }
//            notifyDataSetChanged();
        }
    }


    class Holder extends RecyclerView.ViewHolder {

        private RelativeLayout rl;  //消息
        private ImageView img_icon; //头像
        private TextView read_msg;  //未读消息
        private TextView tv_title;  //标题
        private TextView tv_content;    //内容
        private TextView tv_time;   //消息时间

        private Button btn_topping; //置顶按钮
        private Button btn_read;    //标为已读
        private Button btn_delete;  //删除

        public Holder(@NonNull View itemView) {
            super(itemView);

            rl = (RelativeLayout) itemView.findViewById(R.id.msg);
            img_icon = (ImageView) itemView.findViewById(R.id.iv_img);
            read_msg = (TextView) itemView.findViewById(R.id.read_msg);
            tv_title = (TextView) itemView.findViewById(R.id.title);
            tv_content = (TextView) itemView.findViewById(R.id.content);
            tv_time = (TextView) itemView.findViewById(R.id.time);
            btn_topping = (Button) itemView.findViewById(R.id.topping);
            btn_read = (Button) itemView.findViewById(R.id.read);
            btn_delete = (Button) itemView.findViewById(R.id.delete);

        }
    }
}
